package com.szh.mysobproject.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.util.Log
import androidx.activity.viewModels
import androidx.core.content.getSystemService
import androidx.lifecycle.lifecycleScope
import androidx.paging.PagingData
import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import by.kirich1409.viewbindingdelegate.viewBinding
import com.hjq.umeng.Platform
import com.hjq.umeng.UmengShare
import com.szh.mysobproject.R
import com.szh.mysobproject.action.StatusAction
import com.szh.mysobproject.aop.DebugLog
import com.szh.mysobproject.app.AppActivity
import com.szh.mysobproject.databinding.FishListFragmentBinding
import com.szh.mysobproject.databinding.FishPondDetailActivityBinding
import com.szh.mysobproject.manager.UserManager
import com.szh.mysobproject.model.Fish
import com.szh.mysobproject.model.FishPondComment
import com.szh.mysobproject.other.IntentKey
import com.szh.mysobproject.other.KeyboardWatcher
import com.szh.mysobproject.ui.adapter.AdapterDelegate
import com.szh.mysobproject.ui.adapter.EmptyAdapter
import com.szh.mysobproject.ui.adapter.FishListAdapter
import com.szh.mysobproject.ui.adapter.FishPondDetailCommentListAdapter
import com.szh.mysobproject.ui.dialog.MessageDialog
import com.szh.mysobproject.ui.dialog.ShareDialog
import com.szh.mysobproject.ui.fragment.SubmitCommentFragment
import com.szh.mysobproject.util.*
import com.szh.mysobproject.viewmodel.KeyboardViewModel
import com.szh.mysobproject.viewmodel.fishpond.FishPondViewModel
import com.szh.mysobproject.widget.StatusLayout
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import kotlinx.coroutines.flow.collectLatest
import timber.log.Timber

/**
 * @author : create by  szh
 * @date : 2022/6/27 15:38
 * @desc :鱼塘详情
 */

class FishPondDetailActivity : AppActivity(), StatusAction,
    KeyboardWatcher.SoftKeyboardStateListener {

    private val mBinding: FishPondDetailActivityBinding by viewBinding()
    private val mFishPondViewModel by viewModels<FishPondViewModel>()
    private val mKeyboardViewModel by viewModels<KeyboardViewModel>()
    private val mAdapterDelegate = AdapterDelegate()
    private val mFishListAdapter = FishListAdapter(AdapterDelegate(), true)
    private val mFishPondDetailCommendListAdapter =
        FishPondDetailCommentListAdapter(mAdapterDelegate)

    private var mMomentId: String = ""
    private var mNickName: String = ""

    private var isShowing = false
    private var clickLogin = false


    override fun getLayoutId(): Int = R.layout.fish_pond_detail_activity

    override fun initView() {
        // This emptyAdapter is like a hacker.
        // Its existence allows the PagingAdapter to scroll to the top before being refreshed,
        // avoiding the problem that the PagingAdapter cannot return to the top after being refreshed.
        // But it needs to be used in conjunction with ConcatAdapter, and must appear before PagingAdapter.
        val emptyAdapter = EmptyAdapter()
        val concatAdapter =
            ConcatAdapter(emptyAdapter, mFishListAdapter, mFishPondDetailCommendListAdapter)
        mBinding.rvFishPondDetailComment.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = concatAdapter
            addItemDecoration(SimpleLinearSpaceItemDecoration(1.dp))
        }
        postDelayed({
            KeyboardWatcher.with(this)
                .setListener(this)
        }, 500)
    }

    override fun onSoftKeyboardOpened(keyboardHeight: Int) {
        mKeyboardViewModel.showKeyboard()
        mKeyboardViewModel.setKeyboardHeight(keyboardHeight)
    }

    override fun onSoftKeyboardClosed() {
        mKeyboardViewModel.hideKeyboard()
    }

    private fun safeShowFragment(targetUserName: String) {
        val args = SubmitCommentFragment.getCommentArgs(
            targetUserName,
            mMomentId,
            "",
            "",
            false
        )
        val dialogFragment = SubmitCommentFragment()
        dialogFragment.arguments = args
        dialogFragment.show(supportFragmentManager, dialogFragment.tag)
    }

    override fun initData() {
        showLoading()
        mMomentId = intent.getStringExtra(IntentKey.ID) ?: ""
        loadFishDetail()
        lifecycleScope.launchWhenCreated {
            mFishPondViewModel.getFishCommendListById(mMomentId).collectLatest {
                mFishPondDetailCommendListAdapter.submitData(it)
                mBinding.rvFishPondDetailComment.scrollToPosition(0)
            }
        }
    }

    fun refreshFishPondDetailCommendList() {
        mFishPondDetailCommendListAdapter.refresh()
    }

    private fun loadFishDetail() = mFishPondViewModel.getFishDetailById(mMomentId).observe(this) {
        mBinding.slFishDetailRefresh.finishRefresh()
        val item = it.getOrElse {
            showError {
                initData()
            }
            return@observe
        }
        mNickName = item.nickname
        mFishListAdapter.submitData(lifecycle, PagingData.from(listOf(item)))
        showComplete()
        mBinding.commentContainer.clReplyContainer.setFixOnClickListener {
            goToPostComment(mNickName)
        }
    }


    private fun dynamicLikes(item: Fish.FishItem, position: Int) {
        val currUserId = UserManager.loadCurrUserId()
        //检查是否登录
        if (currUserId.isNotEmpty()) {
            val thumbUpList = item.thumbUpList
            if (thumbUpList.contains(currUserId)) {
                toast("请不要重复点赞")
            } else {
                thumbUpList.add(currUserId)
                mFishListAdapter.notifyItemChanged(position)
            }
            tryVibrate()
            mFishPondViewModel.dynamicLikes(item.id).observe(this) {}
        } else {

            if (isShowing) {
                return
            }
            MessageDialog.Builder(context)
                .setTitle("系统消息")
                .setMessage("账号未登录，是否登录？")
                .setConfirm("现在登录")
                .setCancel("暂不登录")
                .addOnShowListener {
                    isShowing = true
                }
                .addOnDismissListener {
                    isShowing = false
                }
                .setListener {
                    LoginActivity.start(context, "", "")
                }.show()
        }
    }

    @SuppressLint("MissingPermission")
    private fun tryVibrate() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            getSystemService<Vibrator>()?.let { vibrator ->
                if (vibrator.hasVibrator()) {
                    val ve = VibrationEffect.createOneShot(
                        80,
                        VibrationEffect.DEFAULT_AMPLITUDE
                    )
                    vibrator.vibrate(ve)
                }
            }
        }
    }

    private fun shareFish(item: Fish.FishItem) {
        val momentId = item.id
        val content = UMWeb(SUNNY_BEACH_FISH_URL_PRE + momentId)
        content.title = "我发布了一条摸鱼动态，快来看看吧~"
        content.setThumb(UMImage(this, R.mipmap.launcher_ic))
        content.description = getString(R.string.app_name)
        // 分享
        ShareDialog.Builder(this)
            .setShareLink(content)
            .setListener(object : UmengShare.OnShareListener {
                override fun onSucceed(platform: Platform) {
                    toast("分享成功")
                }

                override fun onError(platform: Platform, t: Throwable) {
                    toast(t.message)
                }

                override fun onCancel(platform: Platform) {
                    toast("分享取消")
                }
            })
            .show()
    }


    override fun initEvent() {
        mFishListAdapter.setOnMenuItemClickListener { view, item, position ->
            when (view.id) {
                R.id.ll_share -> shareFish(item)
                R.id.ll_great -> dynamicLikes(item, position)
            }
        }
        mFishListAdapter.setOnNineGridClickListener { sources, index ->
            ImagePreviewActivity.start(this, sources, index)
        }
        mBinding.slFishDetailRefresh.setOnRefreshListener {
            // 加载摸鱼动态详情和摸鱼动态评论列表
            loadFishDetail()
            mFishPondDetailCommendListAdapter.refresh()
        }
        mBinding.slFishDetailRefresh.setEnableLoadMore(false)
        mFishPondDetailCommendListAdapter.setOnVewMoreClickListener { item, position ->
            viewMoreDetail(item)
        }
        mFishPondDetailCommendListAdapter.setOnCommentClickListener { item, position ->
            viewMoreDetail(item)
        }
        mBinding.commentContainer.tvFishPondSubmitComment.setFixOnClickListener {
            goToPostComment(mNickName)
        }
    }

    private fun viewMoreDetail(item: FishPondComment.FishPondCommentItem) {
        val intent = FishCommendDetailActivity.getIntent(this, mMomentId, item)
        startActivityForResult(intent) { resultCode, _ ->
            if (resultCode == RESULT_OK) {
                mFishPondDetailCommendListAdapter.refresh()
            }
        }
    }

    private fun goToPostComment(targetUserName: String) {
        takeIfLogin {
            safeShowFragment(targetUserName)
        }
    }

    override fun getStatusLayout(): StatusLayout = mBinding.slFishDetailHint

    override fun isStatusBarDarkFont(): Boolean = false

    companion object {
        @JvmStatic
        @DebugLog
        fun start(context: Context, momentId: String) {
            val intent = Intent(context, FishPondDetailActivity::class.java)
            intent.putExtra(IntentKey.ID, momentId)
            if (context !is Activity) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            context.startActivity(intent)
        }
    }

}